package br.com.dev.tcc.view.dialog;

import java.util.Calendar;

import android.app.Dialog;
import android.content.Context;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import br.com.dev.tcc.R;

public class DatePickerDialog extends Dialog {

	private DatePicker datePicker;
	private Button btSelecionar;
	private Button btCancelar;

	public DatePickerDialog(Context context, final OnDatePickerListener listener) {

		super(context, R.style.DialogAppTheme);

		super.getWindow();
		super.requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.setContentView(R.layout.date_picker_dialog);

		datePicker = (DatePicker) findViewById(R.id.datePicker);

		btSelecionar = (Button) findViewById(R.id.btSelecionar);
		btSelecionar.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				listener.onDateSelected(getDate());
				dismiss();
			}
		});

		btCancelar = (Button) findViewById(R.id.btCancelar);
		btCancelar.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				dismiss();
			}
		});
	}

	private String getDate() {

		Calendar max = Calendar.getInstance();
		Calendar selected = Calendar.getInstance();
		selected.set(Calendar.DAY_OF_MONTH, datePicker.getDayOfMonth());
		selected.set(Calendar.MONTH, datePicker.getMonth());
		selected.set(Calendar.YEAR, datePicker.getYear());

		if (selected.getTimeInMillis() > max.getTimeInMillis())
			selected = max;

		String dayOfMonth = Integer.toString(selected
				.get(Calendar.DAY_OF_MONTH));
		int month = selected.get(Calendar.MONTH);
		String year = Integer.toString(selected.get(Calendar.YEAR));

		if (dayOfMonth.length() == 1)
			dayOfMonth = "0" + dayOfMonth;

		month = (month + 1) % 12;

		if (month == 0) {
			month = 12;
		}
		
		String strMonth = Integer.toString(month);
		if (strMonth.length() == 1)
			strMonth = "0" + strMonth;

		String data = dayOfMonth + "/" + strMonth + "/" + year;
		return data;
	}

	public interface OnDatePickerListener {
		public void onDateSelected(String date);
	}
}
